using Godot;
using System;

public partial class ThrowSword : Node,StateNode
{
	public Enemy enemy;

	public Sword sword;

	//在动画结束后，转换计时器
	public Timer timer;

	//扔剑计时器
	public Timer timerSword;

	public AnimatedSprite2D animaEnemy;

    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
	{
		enemy = GetNode<Enemy>("/root/Main/Enemy");

		animaEnemy = enemy.GetNode<AnimatedSprite2D>("AnimaEnemy");
		animaEnemy.AnimationFinished+=OnThrowSwordFinished;

		sword = enemy.GetNode<Sword>("Weapons/Sword");

		timer = GetNode<Timer>("Timer");
		timer.Timeout+=OnTimeout;

		timerSword = GetNode<Timer>("TimerSword");
		timerSword.Timeout+=OnTimerSwordOut;
	}

    private void OnTimerSwordOut()
    {
        sword.OnThrowSword();
    }

    private void OnTimeout()
	{
		float num_rand = MyUtil.RangeRandom(0, 100);
		if (enemy.Health > 5)
		{
			if (num_rand <= 50)
				enemy.SwitchTo("Squat");
			else if (num_rand <= 80)
			{
				if(!enemy.IsOnFloor())
					enemy.SwitchTo("Fall");
				else
					enemy.SwitchTo("Jump");
			}
			else
				enemy.SwitchTo("Idle");
		}
		else
		{
			if (num_rand <= 50)
			{
				if(!enemy.IsOnFloor())
					enemy.SwitchTo("Fall");
				else
					enemy.SwitchTo("Jump");
			}
			else if (num_rand <= 80)
				enemy.SwitchTo("Throw_silk");
			else
				enemy.SwitchTo("Idle");
		}
	}

    private void OnThrowSwordFinished()
    {
		if(animaEnemy.Animation == "throw_sword")
		{
			timer.WaitTime = MyUtil.RangeRandom(0.5f,1.0f);
			timer.Start();
			animaEnemy.Animation = "idle";
		}
    }

    public void OnEnter()
    {
        animaEnemy.Animation = "throw_sword";
		timerSword.Start();
    }

    public void OnExit()
    {
    }

    public void OnUpdate(float delta)
    {
        if(enemy.Health<=0)
			enemy.SwitchTo("Dead");
    }
}
